/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.freddy.chat.slice;

import com.freddy.chat.ResourceTable;
import com.freddy.chat.bean.SingleMessage;
import com.freddy.chat.event.CEventCenter;
import com.freddy.chat.event.Events;
import com.freddy.chat.event.I_CEventListener;
import com.freddy.chat.im.IMSClientBootstrap;
import com.freddy.chat.im.MessageProcessor;
import com.freddy.chat.im.MessageType;
import com.freddy.chat.utils.CThreadPoolExecutor;
import com.freddy.im.NettyServerDemo;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.global.resource.NotExistException;
import ohos.global.resource.ResourceManager;
import ohos.global.resource.WrongTypeException;

import java.io.IOException;
import java.util.UUID;

/**
 * MainAbilitySlice
 *
 * @since 2021-04-13
 */
public class MainAbilitySlice extends AbilitySlice implements I_CEventListener {
    private static final String[] EVENTS = {
            Events.CHAT_SINGLE_MESSAGE
    };

    private static final String USER_ID = "100002";
    private static final String TOKEN = "token_" + USER_ID;
    private static final String HOSTS = "[{\"host\":\"192.168.3.12\", \"port\":8855}]";
    private TextField mEditText;
    private Button mSendMsg;
    private Text mTextView;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        ResourceManager resManager = this.getResourceManager();
        try {
            int color = resManager.getElement(ResourceTable.Color_colorPrimaryDark).getColor();
            getWindow().setStatusBarColor(color);
        } catch (IOException | NotExistException | WrongTypeException e) {
            e.fillInStackTrace();
        }

        mEditText = (TextField) findComponentById(ResourceTable.Id_et_content);
        mSendMsg = (Button) findComponentById(ResourceTable.Id_bt_send_msg);
        mTextView = (Text) findComponentById(ResourceTable.Id_tv_msg);

        CThreadPoolExecutor.runInBackground(NettyServerDemo::startServer);

        mSendMsg.setClickedListener(component -> sendMsg());

        IMSClientBootstrap.getInstance().init(USER_ID, TOKEN, HOSTS, 1);

        CEventCenter.registerEventListener(this, EVENTS);
    }

    @Override
    protected void onStop() {
        super.onStop();
        CEventCenter.unregisterEventListener(this, EVENTS);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    private void sendMsg() {
        SingleMessage message = new SingleMessage();
        message.setMsgId(UUID.randomUUID().toString());
        message.setMsgType(MessageType.SINGLE_CHAT.getMsgType());
        message.setMsgContentType(MessageType.MessageContentType.TEXT.getMsgContentType());
        message.setFromId(USER_ID);
        message.setToId("100001");
        message.setTimestamp(System.currentTimeMillis());
        message.setContent(mEditText.getText());

        MessageProcessor.getInstance().sendMsg(message);
    }

    @Override
    public void onCEvent(String topic, int msgCode, int resultCode, Object obj) {
        if (Events.CHAT_SINGLE_MESSAGE.equals(topic)) {
            final SingleMessage message = (SingleMessage) obj;
            CThreadPoolExecutor.runOnMainThread(() -> mTextView.setText(message.getContent()));
        }
    }
}
